package locations.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import locations.dao.DAOFactory;
import locations.dao.InstitutionTypeDAO;
import locations.model.InstitutionType;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class SaveInstitutionTypeAction extends ActionSupport 
    implements ModelDriven<InstitutionType>, ServletRequestAware, ServletResponseAware {
	
	private static final long serialVersionUID = -8124967730231198191L;
	
	private HttpServletRequest request; 
	private HttpServletResponse response; 
	private InstitutionType institutionType = new InstitutionType();
	
	public String execute(){
		InstitutionTypeDAO dao = DAOFactory.getInstitutionTypeDAO();
		dao.save(this.institutionType);
		return SUCCESS;
	}
	
	@Override
	public InstitutionType getModel() {
		return this.institutionType;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public InstitutionType getInstitutionType() {
		return institutionType;
	}

	public void setInstitutionType(InstitutionType institutionType) {
		this.institutionType = institutionType;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public HttpServletResponse getResponse(){
		return this.response;
	}
        
        public void validate()
        {
            boolean ok = true;
            if (this.getInstitutionType().getName().equals(""))
            {
                addFieldError("nombre", "El nombre no puede estar en blanco");
                    ok = false;
            }
            if (ok)
            {
                InstitutionTypeDAO dao = DAOFactory.getInstitutionTypeDAO();
                long auxId = (this.getInstitutionType().getId() == null? 0 : this.getInstitutionType().getId());
                if (dao.exists(this.getInstitutionType().getName(), auxId))
                {
                    addFieldError("nombre", "Ya existe un tipo de institución con ese nombre");
                    ok = false;
                }
            }
        }
}
